package ynu.lcy.elememicroservicegateway.utils;

import com.auth0.jwt.JWT;
import com.auth0.jwt.JWTVerifier;
import com.auth0.jwt.algorithms.Algorithm;
import com.auth0.jwt.exceptions.JWTVerificationException;
import com.auth0.jwt.exceptions.TokenExpiredException;
import com.auth0.jwt.interfaces.DecodedJWT;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.core.io.buffer.DataBuffer;
import org.springframework.core.io.buffer.DataBufferFactory;
import org.springframework.http.HttpStatus;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.stereotype.Component;
import reactor.core.publisher.Mono;
import ynu.lcy.elememicroservicecommon.constant.CommonConstant;
import ynu.lcy.elememicroservicecommon.exception.BusinessException;
import ynu.lcy.elememicroservicecommon.utils.BaseResponse;
import ynu.lcy.elememicroservicecommon.utils.ErrorCode;

import java.nio.charset.StandardCharsets;

@Component
public class CommonUtils {


    private static final ObjectMapper objectMapper = new ObjectMapper();
    /**
     * 构建响应
     *  @param response 响应
     *  @param status 状态码
     *  @param errorCode 错误码
     *  @return 响应
     * */
    public static Mono<Void>  buildErrorResponse(ServerHttpResponse response, HttpStatus status, ErrorCode errorCode) {
        response.setStatusCode(status);
        response.getHeaders().add("Content-Type", "application/json;charset=UTF-8");
        DataBufferFactory dataBufferFactory = response.bufferFactory();
        BaseResponse errorResponse = new BaseResponse(errorCode);
        try {
            DataBuffer dataBuffer = dataBufferFactory.wrap(objectMapper.writeValueAsBytes(errorResponse));
            return response.writeWith(Mono.just(dataBuffer));
        } catch (Exception e) {
            DataBuffer dataBuffer = dataBufferFactory.wrap("内部错误".getBytes(StandardCharsets.UTF_8));
            return response.writeWith(Mono.just(dataBuffer));
        }
    }


    /**
     * 获取token
     * @param request 请求
     * @return token
     * */
    public static String extractToken(ServerHttpRequest request) {
        // 尝试从请求头中提取token
        String authHeader = request.getHeaders().getFirst("token");
        if (authHeader != null) {
            return authHeader;
        }
        // 如果请求头中没有找到token，则尝试从请求路径参数中提取
        return request.getQueryParams().getFirst("token");
    }

    /**
     * 校验token
     * @param token token
     * */
    public static DecodedJWT validateToken(String token){
        DecodedJWT decodedJWT;
        try {
            //判断有效性和时效性
            JWTVerifier verifier = JWT.require(Algorithm.HMAC256(CommonConstant.SECRET))
                    .withIssuer(CommonConstant.ISSUER)
                    .build();
            decodedJWT = verifier.verify(token);
            return decodedJWT;
        } catch (TokenExpiredException e) {
            //token过期
            return null;
        } catch (JWTVerificationException e) {
            //token无效
            return null;
        }
    }
}
